/*
 * Copyright (C) 2009, 2010, B3log Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.b3log.nide.util.parser.java.source;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.b3log.nide.util.parser.Style;
import org.b3log.nide.util.parser.marker.HighlightingMarker;

/**
 * Comment visitor.
 *
 * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
 * @version 1.0.0.1, Nov 29, 2010
 */
public final class CommentVisitor {

    /**
     * Logger.
     */
    private static final Logger LOGGER =
            Logger.getLogger(CommentVisitor.class.getName());
    /**
     * Highlighting marker.
     */
    private Set<HighlightingMarker> highlightingMarkers =
            new HashSet<HighlightingMarker>();
    /**
     * Java source code.
     */
    private String javaSourcecode;
    /**
     * Comment pattern.
     */
    private static final Pattern REGEX_COMMENT = Pattern.compile(
            "(?ms)/\\*.*?\\*/|^\\s*//.*?$");
    /**
     * Comment style.
     */
    private static final Style COMMENT_STYLE = new Style();

    static {
        COMMENT_STYLE.setColor("#808080");
    }

    /**
     * Constructs a {@code CommentVisitor} object with the specified Java
     * source code.
     *
     * @param javaSourcecode the specified Java source code
     */
    public CommentVisitor(final String javaSourcecode) {
        this.javaSourcecode = javaSourcecode;

        visitComments();
    }

    /**
     * Gets the source markers of comment highlighting.
     *
     * @return source markers of comment highlighting
     */
    public Set<HighlightingMarker> getHighlightingMarkers() {
        return Collections.unmodifiableSet(highlightingMarkers);
    }

    /**
     * Visits comments.
     */
    private void visitComments() {
        final Matcher matcher = REGEX_COMMENT.matcher(javaSourcecode);
        while (matcher.find()) {
            final String comment = matcher.group();

            for (int i = 0; i < comment.length(); i++) {
                final HighlightingMarker highlightingMarker =
                        new HighlightingMarker(matcher.start() + i);
                highlightingMarker.setStyle(COMMENT_STYLE);

                highlightingMarkers.add(highlightingMarker);
            }
        }
    }
}
